package correctionRecherche;

import java.util.ArrayList;
import java.util.HashSet;


public class RechercheApproximative {

    private String buildRequest(String[] lstMots) {
        String tmp = " ( ";
        for (int i = 0; i < lstMots.length; i++) {
            if (i == lstMots.length - 1) {
                tmp += " " + lstMots[i];
            } else {
                tmp += " " + lstMots[i] + " OR";
            }
        }


        return tmp + " )";
    }

    private ArrayList<String> getWordInRequest(String query) {
        ArrayList<String> tmpQuery = new ArrayList<>();

        //SUPPRESSION DES EXPRESSIONS BOOLEENS
        for (String s : query.split(" ")) {
            if (!(s.contains("AND") || s.contains("OR") || s.contains("NOT") || s.contains("(") || s.contains(")"))) {
                tmpQuery.add(s);
            }
        }

        return tmpQuery;
    }

    private int LevenshteinDistance(String s, String t) {
        int len_s = s.length(), len_t = t.length(), cost = 0;

        if (s.toCharArray()[0] != t.toCharArray()[0]) {
            cost = 1;

        }
        if (len_s == 0) {
            return len_t;
        } else if (len_t == 0) {
            return len_s;
        } else {
            return Math.min(Math.min(
                    LevenshteinDistance(s.substring(1), t) + 1,
                    LevenshteinDistance(s, t.substring(1)) + 1),
                    LevenshteinDistance(s.substring(1), t.substring(1)) + cost);
        }

    }

    public String getCorrection(String query) {
        HashSet<String> loadMots = IndexReader.getVocab();
        ArrayList<String> lstMots = getWordInRequest(query);
        ArrayList<String> tmpMots = new ArrayList<>();

        lstMots.removeAll(loadMots);

        for (String s : lstMots) {
            tmpMots.clear();
            for (String t : loadMots) {
                if (LevenshteinDistance(s, t) < s.length() * 2.0 / 3) {
                    tmpMots.add(t);
                }
            }
            query.replace(s, buildRequest((String[]) tmpMots.toArray()));
        }
        return query;
    }
}
